package com.hyt.it.ogt.ks.service.impl;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

import javax.annotation.Resource;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.hyt.common.apiInfor.ApiResponse;
import com.hyt.core.base.BaseServiceImpl;
import com.hyt.it.ogt.ks.api.kw.model.CandidateLogDTO;
import com.hyt.it.ogt.ks.config.KsBizRunTimeException;
import com.hyt.it.ogt.ks.enums.BizStatusCode;
import com.hyt.it.ogt.ks.feign.KwClient;
import com.hyt.it.ogt.ks.mapper.CandidateLogBackupMapper;
import com.hyt.it.ogt.ks.mapper.CandidateLogMapper;
import com.hyt.it.ogt.ks.model.entity.CandidateLog;
import com.hyt.it.ogt.ks.model.entity.CandidateLogBackup;
import com.hyt.it.ogt.ks.service.ICandidateLogBackupService;

import lombok.extern.slf4j.Slf4j;

/**
 * @author wuyingge
 * @ClassName CandidateLogBackupServiceImpl.java
 * @Description 考生考试操作轨迹，包括作答日志、登录、提交答案、切换屏幕、复制粘贴等 服务实现类
 * @createTime 2021年11月26日 10:28:00
 */
@Service
@Slf4j
public class CandidateLogBackupServiceImpl extends BaseServiceImpl<CandidateLogBackupMapper, CandidateLogBackup>
        implements ICandidateLogBackupService {
    @Resource
    private CandidateLogBackupMapper candidateLogBackupMapper;
    @Resource
    private CandidateLogMapper candidateLogMapper;
    @Resource
    private KwClient kwClient;

    /**
     * 获取考生事件接口
     * @param candidateId
     * @return
     */
    @Override
    public List<CandidateLogDTO> getCandidateExamLogDetail(String candidateId){
        return candidateLogBackupMapper.getCandidateExamLogDetail(candidateId);
    }

    /**
     * 定时备份考生事件表
     */
    @Override
    public Boolean taskBackupCandidateLogTable(String... candidateIds){
        if(Objects.isNull(candidateIds) || candidateIds.length == 0){
            log.info("--------收到考生事件记录备份操作，考生id集合为空------");
            return Boolean.FALSE;
        }
        log.info("-----收到考生事件记录备份操作，考生id集合数量为:{}",candidateIds.length);
        List<String> cIds = new ArrayList<>(candidateIds.length);
        Collections.addAll(cIds,candidateIds);
        //1:查询当前考生是否有事件记录，有则查出来
        LambdaQueryWrapper<CandidateLog> logQuery = Wrappers.lambdaQuery();
        logQuery.in(CandidateLog::getCandidateId,cIds);
        List<CandidateLog> logs = candidateLogMapper.selectList(logQuery);
        if(CollectionUtils.isEmpty(logs)){
            log.warn("--------收到考生事件记录备份操作，考生事件无记录------");
            return Boolean.TRUE;
        }
        //2:转成备份表实体
        List<CandidateLogBackup> logBackups = new ArrayList<>(logs.size());
        logs.stream().forEach(l -> {
            CandidateLogBackup backup = new CandidateLogBackup();
            BeanUtils.copyProperties(l,backup);
            logBackups.add(backup);
        });
        //3：存入备份表
        candidateLogBackupMapper.batchSave(logBackups);
        //4:更新考生表备份字段
        String updateRsp = kwClient.updateExamCandidateLogIsBackup(cIds);
        log.info("调用考务系统更新考生答题表备份字段，收到返回信息为：【{}】",updateRsp);
        if(StringUtils.isBlank(updateRsp)){
            log.error("--------收到考生事件记录备份操作，备份完成，更新考试考生表字段状态失败------");
            throw new KsBizRunTimeException(BizStatusCode.UPDATE_CANDIDATE_BACKUP_ERROR.getCode(),
                    BizStatusCode.UPDATE_CANDIDATE_BACKUP_ERROR.getMsg());
        }
        ApiResponse<Boolean> updateResponse = ApiResponse.ConvertRet(updateRsp,Boolean.class);
        if(!Objects.equals(updateResponse.getCode(),BizStatusCode.KW_SUCCESS_OK.getCode()) || !Objects.equals(Boolean.TRUE,updateResponse.getData())){
            log.error("--------收到考生事件记录备份操作，备份完成，更新考试考生表字段状态失败,kw返回信息为:【{}】------",updateResponse);
            throw new KsBizRunTimeException(BizStatusCode.UPDATE_CANDIDATE_BACKUP_ERROR.getCode(),
                    BizStatusCode.UPDATE_CANDIDATE_BACKUP_ERROR.getMsg());
        }
        //5：清除原表中的记录
        List<String> logIds = logs.stream().map(CandidateLog::getId).collect(Collectors.toList());
        candidateLogMapper.deleteBatchIds(logIds);
        return Boolean.TRUE;
    }
}
